# -*- coding:utf-8 -*-
"""
图书列表里自定义组件
"""
import os.path
import logging

from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QWidget
from PyQt5.QtGui import QPixmap

from LibrarySystem.config.config import Config

from LibrarySystem.repositories.mongodb.models.book_models import Book

from LibrarySystem.services.ServicesHelper import ServicesHelper

from LibrarySystem.views.ui.BookDetail import Ui_BookDetail
from LibrarySystem.views.components.q_signals import q_signals
from LibrarySystem.views.components.messager import Messager

module_logger = logging.getLogger("logger.sub")


class BookDetail(QWidget, Ui_BookDetail):
    """
    @ClassName：BookDetail
    @Description：BookDetail 映射一本书的信息，用于查询界面创建列表单元，可以存在多个
    负责一本书籍的借阅或归还操作，初始化时接收一个书籍类，以及角色
    @Author：锦沐Python
    """

    def __init__(self, book: Book, role):
        super().__init__()
        self.setupUi(self)
        self.config = Config()
        if self.config.Book_QSS:
            self.setStyleSheet(self.config.Book_QSS)
        self.messager = Messager()
        self.book = book
        self.role = role

        # 显示图书详细信息
        self.book_name_label.setText(f"{self.book.book_name}")
        self.book_category_label.setText(f"分类:{self.book.category}")
        self.book_id_label.setText(f"ID:{self.book.book_id}")
        self.author_label.setText(f"作者:{self.book.author}")
        self.publisher_label.setText(f"出版社:{self.book.publisher}")
        self.record_time_label.setText(f"录入时间:{self.book.record_time}")
        self.ISBN_label.setText(f"ISBN:{self.book.ISBN}")
        self.publication_date_label.setText(f"出版时间:{self.book.publication_date}")
        self.rent_status_label.setText("未出借" if self.book.borrowed_by == "" else "已出借")
        self.loan_period_label.setText(f"可借天数:{self.book.loan_period}")
        self.due_time_label.setText(f"归还日期:{self.book.due_time}")
        self.borrowed_by_label.setText(f"借阅人ID:{self.book.borrowed_by}")
        self.book_name_label.setTextInteractionFlags(Qt.TextSelectableByMouse)
        self.book_category_label.setTextInteractionFlags(Qt.TextSelectableByMouse)
        self.book_id_label.setTextInteractionFlags(Qt.TextSelectableByMouse)
        self.author_label.setTextInteractionFlags(Qt.TextSelectableByMouse)
        self.publisher_label.setTextInteractionFlags(Qt.TextSelectableByMouse)
        self.record_time_label.setTextInteractionFlags(Qt.TextSelectableByMouse)
        self.ISBN_label.setTextInteractionFlags(Qt.TextSelectableByMouse)
        self.publication_date_label.setTextInteractionFlags(Qt.TextSelectableByMouse)
        self.rent_status_label.setTextInteractionFlags(Qt.TextSelectableByMouse)
        self.loan_period_label.setTextInteractionFlags(Qt.TextSelectableByMouse)
        self.due_time_label.setTextInteractionFlags(Qt.TextSelectableByMouse)
        self.borrowed_by_label.setTextInteractionFlags(Qt.TextSelectableByMouse)

        self.show_book_img()
        self.show_button_init()

    def show_book_img(self):
        """
        根据图书图片信息拼接路径，将图片显示
        """
        try:
            if self.book.img_url:
                fileName = os.path.join(self.config.CURRENT_PATH, self.book.img_url)
                pixmap = QPixmap(fileName)
                pixmap = pixmap.scaled(self.img_label.size(), Qt.IgnoreAspectRatio)
                self.img_label.setPixmap(pixmap)
        except Exception as e:
            module_logger.error(f"图片无法展示:{e}")

    def show_button_init(self):
        """
        根据用户身份隐藏或显示借阅按钮，其中只有普通用户可以看到借阅按钮
        """
        # 获取登录用户的角色信息
        current_role = ServicesHelper.get_role_service().get_current_role()[1]
        if self.role != current_role:
            self.borrow_book_button.deleteLater()
            self.back_book_button.deleteLater()
            return
        # 删除
        self.borrowed_by_label.deleteLater()
        self.due_time_label.deleteLater()

        # 已出借的书籍不显示借阅按钮
        if self.book.borrowed_by == "":
            self.borrow_book_button.clicked.connect(self.borrow_book_by_id)
            self.back_book_button.deleteLater()
        else:
            self.back_book_button.clicked.connect(self.back_book_by_id)
            self.borrow_book_button.deleteLater()

    def borrow_book_by_id(self):
        """
        普通用户借阅图书，如借阅成功将
        更改书籍  borrowed_by 字段为用户 id
        该函数使用多线程
        """
        # 获取用户信息
        (flag, login_user) = ServicesHelper.get_role_service().get_current_user()
        if flag is False:
            msg = login_user
            self.messager.show_error(msg)
            return

        # 借阅
        (flag, msg) = ServicesHelper.get_query_service().borrow_book(book_id=self.book.book_id, user_id=login_user.user_id)

        if flag:
            q_signals.ListWidgetRefrsh_Signal.emit()
        else:
            self.messager.show_info(msg)

        module_logger.info(msg)


    def back_book_by_id(self):
        """
        普通用户归还图书，如归还成功将
        更改书籍 borrowed_by 字段为空字符串：""
        该函数使用多线程
        """
        # 获取用户信息
        (flag, login_user) = ServicesHelper.get_role_service().get_current_user()
        if flag is False:
            msg = login_user
            self.messager.show_error(msg)
            return

        # 归还
        (flag, msg) = ServicesHelper.get_query_service().back_book(book_id=self.book.book_id, user_id=login_user.user_id)

        if flag:
            q_signals.ListWidgetRefrsh_Signal.emit()
        else:
            self.messager.show_info(msg)
        module_logger.info(msg)


